package com.zhang.infrastructure.util;

import com.zhang.infrastructure.model.KingHoodExceptionUtil;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-06 11:50
 **/
public class KingHoodUtil {
    /**
     * <p> 随机概率
     * <p> T是唯一标识，可以是表id或者参与抽取的名字等
     * <p> Integer是相对比例，
     * <p> 比如A,B,C比例是3:3:4，仅仅用B,C进行随机抽取，直接传递B3,C4即可
     *
     * @param in 入参
     * @return 返回唯一标识
     * @author zfj
     * @date 2023/7/7
     */
    public static Long randomChance(Map<Long,Integer> in){
        KingHoodExceptionUtil.isEmpty(in,"入参不能为空");

        int min = in.values().stream().filter(Objects::nonNull).min(Integer::compareTo).orElse(0);
        int change = 50;
        if(min > 50){
            change = 1;
        } else if(min > 0){
            change = 50/min + 1 ;
        }

        List<List<Long>> allList = new ArrayList<>();
        AtomicInteger num = new AtomicInteger(0);
        int finalChange = change;
        in.forEach((k, v)->{
            int number = v * finalChange;
            num.addAndGet(number);
            ArrayList<Long> perList = new ArrayList<>(Collections.nCopies(number, k));
            allList.add(perList);
        });

        ThreadLocalRandom current = ThreadLocalRandom.current();
        ArrayList<Long> resultList = new ArrayList<>();
        for (int i = 0; i < num.get(); i++) {
            int k = current.nextInt(allList.size());
            List<Long> list = allList.get(k);
            int v = current.nextInt(list.size());
            resultList.add( list.remove(v));
            if(CollectionUtils.isEmpty(list)){
                allList.remove(k);
            }
        }

        return resultList.get(current.nextInt(resultList.size()));
    }
}
